# -*- coding: utf-8 -*-
import json

from flask import Flask, request
from Utils.public_func import TeambitionConnect
from Utils.public_func import convert_time_web
from Utils.readconfig import ReadConfig

app = Flask(__name__)


@app.after_request
def cors(environ):
    environ.headers['Access-Control-Allow-Origin'] = '*'
    environ.headers['Access-Control-Allow-Method'] = '*'
    environ.headers['Access-Control-Allow-Headers'] = 'x-requested-with,content-type'
    return environ


@app.route('/api/data', methods=['GET'])
def get_data():
    return_dict = {'statusCode': '200', 'message': 'successful!', 'result': False}
    str_time1, str_time2 = json.dumps(request.values.get('dataTime')).split('&')

    str_time1 = str_time1.strip('"')
    str_time2 = str_time2.strip('"')

    start_date = convert_time_web(str_time1)
    end_date = convert_time_web(str_time2)
    with TeambitionConnect()as t:
        if t.select_data(start_date, end_date):

            return_dict['List'] = t.select_data(start_date, end_date)

            return_dict['result'] = True
            return json.dumps(return_dict, ensure_ascii=False)
        else:
            return return_dict


def run_sever():
    sever_host = ReadConfig().flask_config('sever_host')
    sever_port = ReadConfig().flask_config('sever_port')
    sever_debug = ReadConfig().flask_config('sever_debug')

    app.run(host=sever_host, port=sever_port, debug=sever_debug)
